﻿using Nydus.Model.Interfaces;
using System.Data;
using log4net;

namespace Nydus.Model.Repositories
{
    /// <summary>
    /// Represents unit of work for object repositories.
    /// </summary>
    public class UnitOfWork
    {
        private INydusDataContext context;
        private static readonly ILog log = LogManager.GetLogger(typeof(UnitOfWork));
        
        /// <summary>
        /// Creates new instance of <c>UnitOfWork</c>
        /// </summary>
        public UnitOfWork()
        {
            this.context = new Nydus.Model.NydusEntities();
        }

        /// <summary>
        /// Creates new instance of <c>UnitOfWork</c>
        /// </summary>
        /// <param name="context">Object context</param>
        public UnitOfWork(INydusDataContext context)
        {
            this.context = context;
        }

        /// <summary>
        /// Saves all changes made to the context
        /// </summary>
        public void Save()
        {
            try
            {
                this.context.Save();
            }
            catch (OptimisticConcurrencyException e)
            {
                log.Error("Optimistic concurrency exception", e);
                throw new ConcurrencyException(e);
            }
        }

        /// <summary>
        /// Gets the context
        /// </summary>
        internal INydusDataContext Context
        {
            get { return this.context; }
        }
    }
}
